package com.app.utils;

import org.springframework.data.redis.core.RedisTemplate;

/**
 * 布隆过滤器
 *
 * @author xiaoyu.fang
 * @date 2019/12/24 13:43
 */
public class BloomFilterUtil {

    private static final String BLOOM_KEY = "bloomFilter";

    // 2<<25表示32亿个比特位
    private static final int DEFAULT_SIZE = 2 << 25;
    // 8个数组
    private static final int[] seeds = new int[]{3, 5, 7, 11, 13, 19, 23, 37};

    private SimpleHash[] func = new SimpleHash[seeds.length];

    private RedisTemplate<String, Object> redisTemplate;

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public BloomFilterUtil() {
        for (int i = 0; i < seeds.length; i++) {
            func[i] = new SimpleHash(DEFAULT_SIZE, seeds[i]);
        }
    }

    /**
     * 新增
     *
     * @param value
     */
    public void add(String value) {
        for (SimpleHash f : func) {
            // redisTemplate.opsForValue().increment(String.valueOf(f.hash(value)), 1);
            redisTemplate.opsForSet().add(BLOOM_KEY, f.hash(value));
        }
    }

    /**
     * 判断是否存在
     *
     * @param value
     * @return
     */
    public boolean contains(String value) {
        if (value == null) {
            return false;
        }
        boolean ret = true;
        for (SimpleHash f : func) {
            // ret = ret && redisTemplate.hasKey(String.valueOf(f.hash(value)));
            if (!redisTemplate.opsForSet().isMember(BLOOM_KEY, f.hash(value))) {
                return false;
            }
        }
        return ret;
    }


    public static class SimpleHash {
        private int cap;
        private int seed;

        public SimpleHash(int cap, int seed) {
            this.cap = cap;
            this.seed = seed;
        }

        public int hash(String value) {
            int result = 0;
            int len = value.length();
            for (int i = 0; i < len; i++) {
                result = seed * result + value.charAt(i);
            }
            return (cap - 1) & result;
        }
    }
}
